package cn.ddiancan.auth.handler;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2AccessTokenResponseAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@RequiredArgsConstructor
public class XddAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
        OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
            (OAuth2AccessTokenAuthenticationToken) authentication;
        OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
        Instant expiresAt = accessTokenAuthentication.getAccessToken().getExpiresAt();
        Instant issuedAt = accessTokenAuthentication.getAccessToken().getIssuedAt();
        // 登录成功，设置cookie
        Map<String, String> cookieMap = new HashMap<>();
        String sessionId = request.getSession().getId();
        cookieMap.put("JSESSIONID", sessionId);
        cookieMap.put("accessToken",
            URLEncoder.encode(accessTokenAuthentication.getAccessToken().getTokenValue(), "UTF-8"));
        cookieMap.put("login_flag", "true");
        cookieMap.put("refreshToken", Objects.nonNull(refreshToken) ? refreshToken.getTokenValue() : "");
        cookieMap.put("tokenType", accessTokenAuthentication.getAccessToken().getTokenType().getValue());
        StringBuilder cookiBuilder = new StringBuilder();
        cookieMap.forEach((k, v) -> cookiBuilder.append(k).append("=").append(v).append(";"));
        cookiBuilder.append("Path=/;HttpOnly;Secure;SameSite=Lax;Max-Age=")
            .append(expiresAt.getEpochSecond() - issuedAt.getEpochSecond()).append(";").append("Expires=")
            .append(expiresAt);
        response.setHeader(HttpHeaders.SET_COOKIE, cookiBuilder.toString());
        response.setHeader("JSESSIONID", sessionId);
        // 调用默认的OAuth2AccessTokenResponseAuthenticationSuccessHandler处理成功逻辑
        OAuth2AccessTokenResponseAuthenticationSuccessHandler oAuth2AccessTokenResponseAuthenticationSuccessHandler =
            new OAuth2AccessTokenResponseAuthenticationSuccessHandler();
        oAuth2AccessTokenResponseAuthenticationSuccessHandler.onAuthenticationSuccess(request, response,
            authentication);
    }
}
